package com.example.genturedemo;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class TouchZoomView extends androidx.appcompat.widget.AppCompatTextView {

    private float textSize;

    //保存两个手指前一次的距离
    private float preDist;

    public TouchZoomView(Context context) {
        super(context);
    }

    public TouchZoomView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public TouchZoomView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        if(event.getPointerCount() >= 2){
            if(textSize == 0){
                textSize = this.getTextSize();
            }

            switch (event.getActionMasked()){
                //处理手指按下的事件
                case MotionEvent.ACTION_POINTER_DOWN:
                    //计算两个手指直接的距离
                    preDist = calSpace(event);
                    break;
                case MotionEvent.ACTION_MOVE:
                    //实时计算两个手指之间的距离
                    float curVDist = calSpace(event);
                    //根据两个手指之间的距离计算缩放比
                    zoom(curVDist / preDist);
                    //为下一次的缩放做准备
                    preDist = curVDist;
                    break;
            }
        }

        return true;
    }

    private void zoom(float v) {
        textSize *= v;
        this.setTextSize(px2sp(getContext(),textSize));
    }

    private int px2sp(Context context, float pxValue) {
        float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    private float calSpace(MotionEvent event) {
        float x = event.getX(0) - event.getX(1);
        float y = event.getY(0) - event.getY(1);
        //计算两点之间的距离
        return (float) Math.sqrt( x * x +  y * y );
    }
}
